package com.century.sjt.activity.Pay;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.activity.MyOrderDetailsActivity;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by 炳基 on 2016/8/23.
 */
public class CommodityActivity extends BaseActivity {

    private SjtTitleBar titleBar;
    private WebView mWVcontent;
    private String url;
    private String ShopId,GoodId;

    private Button btn_Order;

    private String shareUrl,goodName,mainImageUrl;
    private LinearLayout layout_bottom;

    private String type;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity);

        initView();
        initEvent();
        initData();
    }

    @Override
    protected void initView() {

        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        titleBar.setTitle(getResources().getString(R.string.tab_commodit_picture));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mWVcontent = (WebView) findViewById(R.id.news_detail_webview );
        btn_Order = (Button) findViewById(R.id.btn_place_an_order);
        layout_bottom = (LinearLayout) findViewById(R.id.layout_bottom);
    }

    @Override
    protected void onResume() {
//        mWVcontent.loadUrl(url);
        super.onResume();
    }

    @Override
    protected void initEvent() {


        SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        String isMerchant = mainSharedPreferences.getString("isMerchant", "");
        String isShop = mainSharedPreferences.getString("isShop", "");
        if ("1".equals(isMerchant)||"1".equals(isShop)){
            layout_bottom.setVisibility(View.GONE);
        }else {
            layout_bottom.setVisibility(View.VISIBLE);
        }
        Intent intent=getIntent();
        url=intent.getStringExtra("url");//商品详情连接
        type = intent.getStringExtra("type");
        if ("service".equals(type)){
            layout_bottom.setVisibility(View.GONE);
        }else {
            titleBar.setRightIconResourc(getResources().getString(R.string.icon_share));
            titleBar.setRightLayoutClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showShare();
                }
            });
            ShopId = intent.getStringExtra("shopId");//商家ID
            GoodId = intent.getStringExtra("goodId");//商品ID
            shareUrl = intent.getStringExtra("shareUrl");//分享链接
            goodName = intent.getStringExtra("goodName");//商品名称
            mainImageUrl = intent.getStringExtra("mainImageUrl");//商品主图
        }
        WebSettings settings = mWVcontent.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        btn_Order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                placeAnOrder();
            }
        });

    }

    @Override
    protected void initData() {

        mWVcontent.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }
        });
        mWVcontent.loadUrl(url);
    }

    //下单
    private void placeAnOrder() {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), CommodityActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.createMyOrderHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {
                        JSONObject data = res.getJSONObject("data");
                        String orderId = data.getString("orderid");
                        if (!(orderId.equals("null"))){
                            Intent intent = new Intent(CommodityActivity.this, MyOrderDetailsActivity.class);
                            intent.putExtra("orderId", orderId);
                            intent.putExtra("falg",1);
                            startActivity(intent);
                        }else{
                            TipUtil.showToast(getResources().getString(R.string.text_please_choose_goods), CommodityActivity.this, 1);
                        }
                    } else {
                        TipUtil.showToast(message, CommodityActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), CommodityActivity.this, 1);
                }
                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), CommodityActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("shopId", ShopId);//分店id
                map.put("goodId", GoodId);//商品id
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }


    public void showShare() {

        ShareSDK.initSDK(CommodityActivity.this);
        OnekeyShare oks = new OnekeyShare();
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitleUrl(shareUrl);
        oks.setTitle(Constant.SHARE_TITLE);
//        String loginid=SjtMainActivity.mainSharePreferences.getString("loginid","");
//        oks.setImagePath(Constant.CAMERA_PICTURE_PATH + loginid);
        oks.setImageUrl(mainImageUrl);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(goodName);
//        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        oks.setUrl(shareUrl);
        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite(getString(R.string.app_name));
        oks.show(CommodityActivity.this);
    }
}
